//  zip.js
const fs = require('fs');

function parseTime(cFormat) {
  let time = new Date();
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/');
      }
    }

    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    return value.toString().padStart(2, '0');
  });
  return time_str;
}

const plugin = function (fileName = 'dist', output, projectName = '') {
  const path = require('path');
  if (!output) output = path.resolve(__dirname, './dist');
  fileName += '.zip';
  const makeZip = function () {
    const path = require('path');
    const fs = require('fs');
    const JSZip = require('jszip');
    const zip = new JSZip();
    const distPath = path.resolve(output);
    const readDir = function (zip, dirPath) {
      // 读取dist下的根文件目录
      const files = fs.readdirSync(dirPath);
      files.forEach(fileName => {
        const fillPath = path.join(dirPath, './', fileName);
        const file = fs.statSync(fillPath);
        // 如果是文件夹的话需要递归遍历下面的子文件
        if (file.isDirectory()) {
          const dirZip = zip.folder(fileName);
          readDir(dirZip, fillPath);
        } else {
          // 读取每个文件为buffer存到zip中
          zip.file(fileName, fs.readFileSync(fillPath));
        }
      });
    };
    const removeExistedZip = () => {
      const dest = path.join(distPath, './' + fileName);
      if (fs.existsSync(dest)) {
        fs.unlinkSync(dest);
      }
    };
    const zipDir = function () {
      readDir(zip, distPath);
      zip.generateAsync({
        type: 'nodebuffer', // 压缩类型
        compression: 'DEFLATE', // 压缩算法
        compressionOptions: { // 压缩级别
          level: 9,
        },
      }).then(content => {
        const dest = path.join(distPath, '../' + parseTime('{m}{d}{h}{i}') + projectName + fileName);
        removeExistedZip();
        // 把zip包写到硬盘中，这个content现在是一段buffer
        fs.writeFileSync(dest, content);
        console.log('打包成功~~~~!!!!')
        console.log('打包文件夹: '+fileName)
        console.log('输出文件夹: '+output)
        console.log('项目名称: '+projectName)
        console.log('输出压缩包: '+parseTime('{m}{d}{h}{i}') + projectName + fileName)
      });
    };
    removeExistedZip();
    zipDir(distPath);
  };

  makeZip();
};
// module.exports = plugin
// const data = fs.readFileSync('./package.json', (data) => {
// });
// const fileRes = data.toString();
// const projectName = fileRes.match(/VITE_APP_CITY_NAME=(.+)/);
// const regRes = fileRes.match(/VITE_APP_OUT_DIR=(.+)/);
// if (regRes) {
//   plugin(regRes[1], regRes[1], projectName[1]);
// }
plugin(undefined,undefined, require('./package.json').projectName)
